//
//  MRJobOrderViewController.m
//  ERP
//
//  Created by goldeney on 15/2/28.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MRJobOrderViewController.h"

#import "AutoTextTableViewCell.h"
#import "NSDictionary+DataFormat.h"
#import "NSString+handle.h"
#import "MRJobOrderViewController.h"
#import "WebServiceCommonRequest.h"

#import "TYMActivityIndicatorView.h"
#import "NSKeyedArchiverUserLogin.h"
#import "MRJobOrderViewCell.h"
#import "MRMixtureRatioDetailController.h"

@interface MRJobOrderViewController ()

@property (nonatomic,strong) NSDictionary *contractBaseInfo;
@property (nonatomic,strong) NSMutableArray *contractData;

@property (nonatomic,strong) NSArray *orderData;
@property (nonatomic,assign) NSInteger orderContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end

@implementation MRJobOrderViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"任务单配合比"];
    }
    return self;
}

- (void)getPassingParameter:(id)object
{
    NSDictionary *dic = object;
    self.contractBaseInfo = dic;
    NSMutableArray *contract = [NSMutableArray array];
    
    [self addContractInfoKey:@"任务单编号" toKey:@"任务单编号：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"状态" toKey:@"任务单状态：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工程名称" toKey:@"工程名称：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"施工部位" toKey:@"施工部位：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"浇筑方式" toKey:@"浇筑方式：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"坍落度" toKey:@"坍  落  度：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"砼强度" toKey:@"砼  标  号：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"施工单位" toKey:@"施工单位：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"工地计划开盘时间" toKey:@"工地计划时间：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"调度计划开盘时间" toKey:@"计划开盘时间：" defaults:@"未知" format:nil form:dic toArray:contract];
    [self addContractInfoKey:@"备注" toKey:@"备       注：" defaults:@"无" format:nil form:dic toArray:contract];
    
    self.contractData = contract;
}

- (void)addContractInfoKey:(id)key toKey:(id)tokey defaults:(id)def format:(id)formatText
                      form:(NSDictionary*)dic toArray:(NSMutableArray*)array
{
    id value = [dic objectFormatForKey:key];
    if (!def) def = @"";
    
    if (!value){
        value = def;
    } else if (formatText) {
        value = [NSString stringWithFormat:formatText,value];
    }
    
    NSDictionary *valueDic = [NSDictionary dictionaryWithObject:value forKey:tokey];
    [array addObject:valueDic];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerClass:[MRJobOrderViewCell class] forCellReuseIdentifier:@"MRJobOrderViewCell"];
    
    //获取任务单所有车辆
    [self getJobOrderInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 网络获取车辆信息
- (void)getJobOrderInfo
{
    //判断是否需要获取订单
    if(!self.contractBaseInfo) return;
    
    //组装条件：1、日期；2、开始行；3、结束行；4、状态
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SYZJ_SGPB_LIST_20151203"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    //设置站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    [content setStationID:[model.stationId integerValue]];
    
    NSString *numberStr = [self.contractBaseInfo objectFormatStringForKey:@"任务单编号"];
    [content addParameterKey:@"任务单编号" value:numberStr];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            NSMutableArray *valueArray = [self dataQueryHandle:result.resultArray];
            self.orderData = valueArray;
            self.orderContentState = 3;
        } else {
            self.orderContentState = 1;
        }
        [self.tableView reloadData];  
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.orderContentState = 2;
        [self.tableView reloadData];
    }];
}

- (NSMutableArray*)dataQueryHandle:(NSArray*)array
{
    //数据查询
    NSMutableArray *compArray = [NSMutableArray arrayWithArray:[array firstObject]];
    NSMutableArray *htArray = [NSMutableArray arrayWithArray:[array lastObject]];
    
    for(int i=0;i<compArray.count;i++){
        NSDictionary *dic = [compArray objectAtIndex:i];
        
        NSInteger clientID = [dic objectFormatIntegerForKey:@"MixerID"];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"MixerID==%ld", clientID];
        NSArray *filteredArray = [htArray filteredArrayUsingPredicate:predicate];
        
        NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [mutableDic setValue:filteredArray forKey:@"itemValue"];
        [compArray setObject:mutableDic atIndexedSubscript:i];
    }
    
    return compArray;
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(self.orderContentState == 3) return self.orderData.count + 1;
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if(self.orderData.count == 0){
        return 1;
    } else if(self.orderContentState == 3){
        NSDictionary *mDictionary = [self.orderData objectAtIndex:section - 1];
        NSArray *array = [mDictionary objectForKey:@"itemValue"];
        return array.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCell"];
        [cell setDataArray:self.contractData];
        return cell;
        
    } else {
        if (self.orderContentState == 3) {
            MRJobOrderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MRJobOrderViewCell" forIndexPath:indexPath];
            
            //车辆信息设置
            NSDictionary *mDictionary = [self.orderData objectAtIndex:indexPath.section - 1];
            NSArray *array = [mDictionary objectForKey:@"itemValue"];
            NSDictionary *itemData = [array objectAtIndex:indexPath.row];
            cell.sjLabel.text = [itemData objectFormatStringForKey:@"上传时间" defaults:@"未知"];
            cell.scxLabel.text = [itemData objectFormatStringForKey:@"上传生产线" defaults:@"未知"];
            cell.ztLabel.text = [itemData objectFormatStringForKey:@"是否上传" defaults:@"未知"];
            cell.bhLabel.text = [itemData objectFormatStringForKey:@"配合比编号" defaults:@"未知"];
            cell.pbrlLabel.text = [itemData objectFormatFloatStringForKey:@"容重" retain:1 format:@"容重%@Kg"];
            
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
            cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
            
            if(self.orderContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 26.5);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"没有配合比信息";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.orderContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载配合比失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if (section == 0) {
        lable.text = @"任务单明细";
    } else if (self.orderData.count <= 0){
        lable.text = @"施工配合比";
    } else {
        NSDictionary *dic = [self.orderData objectAtIndex:section - 1];
        NSString *text = [dic objectFormatStringForKey:@"上传生产线" format:@"%@施工配合比" defaults:@"未知施工配合比"];
        lable.text = text;
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
        [cell setDataArray:self.contractData];
        return cell.contentView.frame.size.height;
    } else if(self.orderData.count == 0){
        return 55;
    } else if(self.orderContentState == 3){
        return 62;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section != 0){
        if(self.orderContentState == 2) {//加载失败执行
            self.orderContentState = 0;
            [self.tableView reloadData];
            [self getJobOrderInfo];
            
        } else if(self.orderContentState == 3){
            //页面跳转
            NSDictionary *mDictionary = [self.orderData objectAtIndex:indexPath.section - 1];
            NSArray *array = [mDictionary objectForKey:@"itemValue"];
            NSDictionary *itemData = [array objectAtIndex:indexPath.row];
            
            MRMixtureRatioDetailController *viewController = [[MRMixtureRatioDetailController alloc] initWithValue:itemData];
            [self.navigationController pushViewController:viewController animated:YES];
        }
    }
}

@end
